package cn.lopr.im.android.mvp.view.fragments;

import android.content.Intent;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;

import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.google.android.material.bottomsheet.BottomSheetBehavior;

import java.util.List;

import cn.lopr.im.android.R;
import cn.lopr.im.android.bean.ArticleCommentVo;
import cn.lopr.im.android.bean.ArticlePlate;
import cn.lopr.im.android.bean.ArticleVo;
import cn.lopr.im.android.bean.PageInfo;
import cn.lopr.im.android.mvp.contact.ICommunityContact;
import cn.lopr.im.android.mvp.presenter.CommunityPresenterImpl;
import cn.lopr.im.android.mvp.view.activities.ArticleViewActivity;
import cn.lopr.im.android.mvp.view.activities.PersonalHomepageActivity;
import cn.lopr.im.android.mvp.view.adapters.CommunityArticleAdapter;
import cn.lopr.im.android.mvp.view.adapters.CommunityPlateAdapter;
import cn.lopr.im.android.mvp.view.dialog.BtnBottomDialog;
import cn.lopr.im.android.mvp.view.dialog.MenuBottomDialog;

public class CommunityFragment extends cn.lopr.im.android.common.app.Fragment implements
        ICommunityContact.ICommunityView {

    private RecyclerView recyclerViewPlate;
    private RecyclerView recyclerViewArticle;
    private CommunityPlateAdapter communityPlateAdapter;
    private CommunityPresenterImpl communityPresenter;
    private BtnBottomDialog btnBottomDialog;
    private List<ArticlePlate> articlePlates;
    private MenuBottomDialog menuBottomDialog;
    private SwipeRefreshLayout refreshLayout;
    private RelativeLayout rlEmpty;
    private CommunityArticleAdapter communityArticleAdapter;
    private String TAG = "demo";
    private String currentPlateId;


    /**
     * 分页
     */
    private int page = 1;
    private int size = 7;
    private boolean isLastPage = false;
    /**
     * 监听是否滑到底部 会一直触发
     */
    private boolean over = false;

    @Override
    protected int getContentLayoutId() {
        return R.layout.fragment_community;
    }

    @Override
    protected void initWidget(View root, LayoutInflater inflater) {
        super.initWidget(root, inflater);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this.getContext()); //LinearLayoutManager中定制了可扩展的布局排列接口，子类按照接口中的规范来实现就可以定制出不同排雷方式的布局了
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);

        this.recyclerViewPlate = root.findViewById(R.id.community_type_list);
        this.recyclerViewPlate.setLayoutManager(layoutManager);
        this.recyclerViewArticle = root.findViewById(R.id.community_article_list);
        this.refreshLayout = root.findViewById(R.id.srl_refresh);
        this.rlEmpty = root.findViewById(R.id.rl_empty);

        this.refreshLayout.setOnRefreshListener(() -> {
            this.page = 1;
            this.communityPresenter.getArticleList(this.getToken(this.getContext()), this.currentPlateId, this.page, this.size);
            this.refreshLayout.setRefreshing(false);
        });

        this.recyclerViewArticle.addOnScrollListener(new RecyclerView.OnScrollListener() {
            int lastVisibleItem = 0;

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                Log.i(TAG, "onScrollStateChanged: " + newState + "end?: "
                        + recyclerView.canScrollVertically(1)
                        + " sor: " + recyclerView.getScrollState()
                        + " end: " + communityArticleAdapter.getItemCount());

                if (!recyclerView.canScrollVertically(1)) {
                    loadMore();
                }

            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = layoutManager.findLastVisibleItemPosition();
            }
        });
    }

    private void loadMore() {
        if (isLastPage || over) {
            return;
        }
        over = true;
        page = page + 1;
        communityArticleAdapter.showLoading();
        new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                communityPresenter.getArticleList(getToken(getContext()), currentPlateId, page, size);
            }
        }.start();

    }

    @Override
    protected void initData() {
        super.initData();
        this.communityPresenter = new CommunityPresenterImpl(this);
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void getPlatesSuccess(List<ArticlePlate> articlePlates) {

        articlePlates.add(0, new ArticlePlate().setId("全部").setName("全部").setCurrent(false));
        if (TextUtils.isEmpty(currentPlateId)) {
            articlePlates.get(0).setCurrent(true);
        } else {
            articlePlates.forEach(e -> {
                if (e.getId().equals(this.currentPlateId)) {
                    e.setCurrent(true);
                }
            });
        }

        this.articlePlates = articlePlates;
        this.communityPlateAdapter = new CommunityPlateAdapter(this.getContext(), articlePlates);
        this.recyclerViewPlate.setAdapter(this.communityPlateAdapter);
        this.communityPlateAdapter.onRecyclerViewItemClickListener(
                new CommunityPlateAdapter.OnRecyclerViewItemClickListener() {
                    @Override
                    public void onItemClick(View view, int section) {
                        ArticlePlate articlePlate = (ArticlePlate) view.getTag();
                        if (view.getId() == R.id.tv_community_plate) {
                            currentPlateId = articlePlate.getId();
                            updatePlateState();
                        }
                    }

                    @Override
                    public void onItemLongClick(View view, int section) {

                    }
                });
    }

    /**
     * 更新板块状态
     */
    void updatePlateState() {
        for (ArticlePlate articlePlate : this.articlePlates) {
            articlePlate.setCurrent(articlePlate.getId().equals(currentPlateId));
        }
        this.page = 1;
        this.communityPresenter.getArticleList(this.getToken(this.getContext()), this.currentPlateId, this.page, this.size);
        this.communityPlateAdapter.refresh(this.articlePlates);
    }

    @Override
    public void getArticleSuccess(PageInfo<ArticleVo> articleVos) {
        over = false;
        if (articleVos == null || articleVos.getList() == null || articleVos.getList().size() == 0) {
            this.rlEmpty.setVisibility(View.VISIBLE);
            this.recyclerViewArticle.setVisibility(View.GONE);
            this.isLastPage = true;
            return;
        } else {
            this.rlEmpty.setVisibility(View.GONE);
            this.recyclerViewArticle.setVisibility(View.VISIBLE);
            this.isLastPage = articleVos.isIsLastPage();
        }

        if (this.communityArticleAdapter != null) {
            this.communityArticleAdapter.showLoadMore();
            this.communityArticleAdapter.refresh(articleVos, this.currentPlateId);
        } else {
            communityArticleAdapter = new CommunityArticleAdapter(this.getContext(), articleVos);
            this.recyclerViewArticle.setAdapter(this.communityArticleAdapter);
        }

        this.communityArticleAdapter.onRecyclerViewItemClickListener(new CommunityArticleAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int section) {
                ArticleVo articleVo = (ArticleVo) view.getTag();
                Log.i("CommunityArticleAdapter", "onItemClick: " + view + " : " + R.id.iv_menu + " id: " + view.getId());

                if (view.getId() == R.id.ll_community_type) {
                    Intent intent = new Intent(getActivity(), ArticleViewActivity.class);
                    intent.putExtra("articleId", articleVo.getId());
                    getActivity().startActivity(intent);

                } else if (view.getId() == R.id.ll_comment) {
                    openBottomDialog(articleVo);

                } else if (view.getId() == R.id.iv_portrait) {
                    getActivity().startActivity(new Intent(getActivity(), PersonalHomepageActivity.class)
                            .putExtra("userId", articleVo.getUserID()));

                } else if (view.getId() == R.id.ll_like) {
                    communityPresenter.updateArticleLikeNum(getToken(getContext()), articleVo.getId(), 1);
                } else if (view.getId() == R.id.iv_menu) {
                    Log.i("CommunityArticleAdapter", "onItemClick: iv_menu " + view.getId());
                    openMenuBottomDialog(articleVo);
                }
            }

            @Override
            public void onItemLongClick(View view, int section) {
            }
        });
    }

    @Override
    public void delArticleSuccess(List<ArticleVo> articles) {

    }

    private void openMenuBottomDialog(ArticleVo articleVo) {
        menuBottomDialog = new MenuBottomDialog(this.getContext(), articleVo.getId());
        menuBottomDialog.show(this.getParentFragmentManager(), "tag");
        menuBottomDialog.onClickListener(new MenuBottomDialog.OnBottomDialogClickListener() {
            @Override
            public void onClick(View view, int section) {
                String articleId = (String) view.getTag();
                if (view.getId() == R.id.tv_del) {
                    communityPresenter.delArticle(getToken(getContext()), articleId);
                    menuBottomDialog.dismiss();
                }
            }

            @Override
            public void onLongClick(View view, int section) {

            }
        });
    }

    private void openBottomDialog(ArticleVo articleVo) {
        btnBottomDialog = new BtnBottomDialog(getContext(), articleVo.getId());
        btnBottomDialog.show(getParentFragmentManager(), "tag");
        btnBottomDialog.onClickListener(new BtnBottomDialog.OnBottomDialogClickListener() {
            @Override
            public void onClick(BottomSheetBehavior<FrameLayout> view, int section) {
                communityPresenter.getArticleList(getToken(getContext()), currentPlateId, page, size);
            }

            @Override
            public void onLongClick(View view, int section) {

            }
        });
    }

    @Override
    public void updateArticleSuccess(String msg) {
        if (communityPresenter != null) {
            this.communityPresenter.getArticleList(this.getToken(this.getContext()), this.currentPlateId, this.page, this.size);
        }
    }

    @Override
    public void getArticleCommentSuccess(List<ArticleCommentVo> articleCommentVos) {
    }

    @Override
    public void onResume() {
        super.onResume();

        if (communityPresenter != null) {
            this.communityPresenter.getPlates(this.getToken(this.getContext()));
            this.communityPresenter.getArticleList(this.getToken(this.getContext()), this.currentPlateId, this.page, this.size);
        }
    }
}